package examples.books

import de.saxsys.mvvmfx.FluentViewLoader
import de.saxsys.mvvmfx.FxmlView
import de.saxsys.mvvmfx.InjectViewModel
import de.saxsys.mvvmfx.utils.viewlist.CachedViewModelCellFactory
import de.saxsys.mvvmfx.utils.viewlist.ViewListCellFactory
import groovy.transform.CompileStatic
import javafx.fxml.FXML
import javafx.fxml.Initializable
import javafx.scene.control.Button
import javafx.scene.control.Label
import javafx.scene.control.ListView
import javafx.scene.control.TextField

import java.util.concurrent.atomic.AtomicInteger

/**
 * Created by Misty on 2015/6/4.
 */
@CompileStatic
class MainView implements FxmlView<MainViewModel>, Initializable {
    @FXML
    private Label titleLabel
    @FXML
    private Label authorLabel
    @FXML
    private TextField searchTextField
    @FXML
    private Button searchButton
    @FXML
    private Label descriptionLabel
    @FXML
    private ListView<BookListItemViewModel> bookList
    @FXML
    private Label errorLabel

    @InjectViewModel
    private MainViewModel viewModel

    @Override
    void initialize(URL location, ResourceBundle resources) {
        def AtomicInteger i = new AtomicInteger(1)

        searchTextField.textProperty().bindBidirectional(viewModel.searchString)
        titleLabel.textProperty().bind(viewModel.bookTitle)
        authorLabel.textProperty().bind(viewModel.bookAuthor)
        descriptionLabel.textProperty().bind(viewModel.bookDescription)

        bookList.setItems(viewModel.books)

        final ViewListCellFactory<BookListItemViewModel> cellFactory = CachedViewModelCellFactory.create({
            BookListItemViewModel vm ->
                println i.getAndIncrement()
                return FluentViewLoader.fxmlView(BookListItemView).viewModel(vm).load()
        })
        bookList.setCellFactory(cellFactory)

        viewModel.selectedBook.bind(bookList.selectionModel.selectedItemProperty())
        errorLabel.textProperty().bind(viewModel.error)

        searchButton.disableProperty().bind(viewModel.searchCommand.notExecutableProperty())
    }

    public void searchButtonPressed() {
        viewModel.searchCommand.execute()
    }
}
